package com.hl.card.modular.packBack.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.hl.card.common.persistence.dao.DisMemberInfoMapper;
import com.hl.card.common.persistence.dao.EnrolmentMapper;
import com.hl.card.common.persistence.dao.PartnerLogMapper;
import com.hl.card.common.persistence.dao.UserMapper;
import com.hl.card.common.persistence.model.DisMemberInfo;
import com.hl.card.common.persistence.model.Enrolment;
import com.hl.card.common.persistence.model.PartnerLog;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.util.ShortMessageUtil;
import com.hl.card.modular.pack.service.DisMemberApplyService;
import com.hl.card.modular.packBack.service.SuperPartnerActiveService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SuperPartnerActiveServiceImpl implements SuperPartnerActiveService {

    private Logger logger=LoggerFactory.getLogger(SuperPartnerActiveServiceImpl.class);

    @Resource(name = "enrolmentMapper")
    private EnrolmentMapper enrolmentMapper;

    @Resource(name = "disMemberInfoMapper")
    private DisMemberInfoMapper disMemberInfoMapper;

    @Autowired
    private ShortMessageUtil shortMessageUtil;

    @Resource(name = "userMapper")
    private UserMapper userMapper;

    @Resource(name = "partnerLogMapper")
    private PartnerLogMapper partnerLogMapper;
    @Resource
    private DisMemberApplyService disMemberApplyService;

    @Override
    public Map<String, Object> transFile(MultipartFile file) {
        String xls_ContentType="application/vnd.ms-excel";
        String xlsx_ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        List<Enrolment> enrolments=new ArrayList<>();
        Map<String, Object> map=new HashMap<>();
        String msg = null;
        String code = "1";
        if (!file.isEmpty()) {
            try {

                String cont = file.getContentType();
                if(cont.equals(xls_ContentType)){
                    logger.info("excel 2003的马甲");
                }else if(cont.equals(xlsx_ContentType)){
                    logger.info("excel 2007的马甲");
                }else{
                    msg="上传格式不正确";
                }
                Workbook book = null;
                try {//2007
                    book = new XSSFWorkbook(file.getInputStream());
                    enrolments  = this.getXlsxData(file.getInputStream());
                } catch (Exception ex) {//2003
                    book = new HSSFWorkbook(file.getInputStream());
                    enrolments  = this.getXlsData(file.getInputStream());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                msg= "上传失败," + e.getMessage();
                code="0";
            } catch (IOException e) {
                e.printStackTrace();
                msg= "上传失败," + e.getMessage();
                code="0";
            }
               msg= "上传成功";
        } else {
            msg="上传失败，因为文件是空的.";
            code="0";
        }
        map.put("code",code);
        map.put("enrolments",enrolments);
        map.put("msg",msg);
        return map;
    }

    @Override
    public List<Enrolment> selectList(Map<String, Object> map) {
        List<Enrolment> list = enrolmentMapper.selectList(map);
        return list;
    }



    public List<Enrolment> getXlsxData(InputStream inputStream) {
        List<Enrolment> varList = new ArrayList<Enrolment>();
        int sheetnum = 0;
        int startrow = 1;
        int startcol = 0;
        try {
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);//xslx
            XSSFSheet sheet = wb.getSheetAt(sheetnum); //sheet 从0开始
            int rowNum = sheet.getLastRowNum() + 1;                     //取得最后一行的行号
            for (int i = startrow; i < rowNum; i++) {                    //行循环开始
                Enrolment enrolment = new Enrolment();
                XSSFRow row = sheet.getRow(i);                             //行
                int cellNum = row.getLastCellNum();                     //每行的最后一个单元格位置
                for (int j = startcol; j < cellNum; j++) {                //列循环开始
                    XSSFCell cell = row.getCell(Short.parseShort(j + ""));
                    String cellValue = null;
                    if (null != cell) {
                        switch (cell.getCellType()) {                     // 判断excel单元格内容的格式，并对其进行转换，以便插入数据库
                            case 0:
//                                cellValue = String.valueOf((int) cell.getNumericCellValue());
                                if(String.valueOf(cell.getNumericCellValue()).indexOf("E")==-1){
                                    cellValue= String.valueOf(cell.getNumericCellValue());
                                }else {
                                    cellValue= new DecimalFormat("#").format(cell.getNumericCellValue());
                                }

                                break;
                            case 1:
                                cellValue = cell.getStringCellValue();
                                break;
                            case 2:
                                cellValue = cell.getNumericCellValue() + "";
                                // cellValue = String.valueOf(cell.getDateCellValue());
                                break;
                            case 3:
                                cellValue = "";
                                break;
                            case 4:
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case 5:
                                cellValue = String.valueOf(cell.getErrorCellValue());
                                break;
                        }
                    } else {
                        cellValue = "";
                    }

                    if (j == 0) {
                        enrolment.setPhone(cellValue);
                    }
                    if (j == 1) {
                        enrolment.setImtoken(cellValue);
                    }
                    if (j == 2) {
                        enrolment.setOrigin(cellValue);
                    }
                    if (j == 3) {
                        enrolment.setGhphone(cellValue);
                    }
                }
                enrolment.setAppendtime(new Date());
                varList.add(enrolment);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(varList);
        return varList;
    }

    @Override
    public void sendmsg(ArrayList<Enrolment> list) {
         for(int i = 0;i < list.size();i++){
             Enrolment enrolment = list.get(i);
             if(enrolment.getStatus() != 2) {
                 try {
                     String code = "SMS_137412324";
                     String hotline = "4009917909";
                     String template = "{\"code\":\"" + enrolment.getActivecode() + "\",\"hotline\":\""+hotline+"\"}";
                     SendSmsResponse sendSmsResponse = shortMessageUtil.sendSms(enrolment.getPhone(), code, template);
                     if (sendSmsResponse.getCode().equals("")) {
                         enrolment.setStatus(2);
                         enrolmentMapper.updateById(enrolment);
                     } else {
                         enrolment.setStatus(1);
                         enrolmentMapper.updateById(enrolment);
                     }
                 } catch (Exception e) {
                 }
             }
         }
    }

    @Override
    public Map<String,Object> insertBatch(List<Enrolment> list) {
        Integer temp = 0;
        String phone = "";
        Map<String, Object> map = new HashMap<>();


        String ghphone = list.get(0).getGhphone();
        User  user=userMapper.selectByPhone(ghphone);
        if (ghphone.equals("")) {
              map.put("failReason","没有群主电话");
              return map;
        } else {
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            DisMemberInfo disMemberInfogh = new DisMemberInfo();
//          disMemberInfogh.setDis_member_no(disMemberApplyService.creatID());
            disMemberInfogh.setStatus(0);
            disMemberInfogh.setDis_recommendation_no(user.getReg_code());
            disMemberInfogh.setAddTime(format.format(date));
            disMemberInfogh.setBinding_phone(ghphone);
            disMemberInfoMapper.insert(disMemberInfogh);


            for (int i = 0; i < list.size(); i++) {
                Enrolment enrolment = list.get(i);
                User user2 = userMapper.selectByPhone(enrolment.getPhone());
                if (user2 != null) {
                    enrolment.setActivecode(user2.getReg_code());
                    enrolment.setAppendtime(new Date());
                    enrolmentMapper.insert(enrolment);
                    temp++;

                } else {
                    PartnerLog partnerLog = new PartnerLog();
                    partnerLog.setAddtime(new Date());
                    partnerLog.setPhone(enrolment.getPhone());
                    partnerLog.setReason("该手机并未注册成为会员");

                    partnerLogMapper.insert(partnerLog);
                    phone += enrolment.getPhone() + ",";
                }
            }
            if (!phone.equals("")) {
                phone = phone.substring(0, phone.length() - 1);
                map.put("failuer", phone);
            }
            map.put("succsscount", temp);
            return map;
        }
    }

    @Override
    public String queryActiveCode(String phone) {
        String activeCode = enrolmentMapper.queryActiveCode(phone);

        return activeCode;
    }

    @Override
    public void delete(Integer id) {
        enrolmentMapper.deleteById(id);
    }

    public List<Enrolment> getXlsData(InputStream inputStream) {
        List<Enrolment> varList = new ArrayList<Enrolment>();
        int sheetnum = 0;
        int startrow = 1;
        int startcol = 0;
        try {
            HSSFWorkbook wb = new HSSFWorkbook(inputStream);//xslx
            HSSFSheet sheet= wb.getSheetAt(sheetnum); //sheet 从0开始

            int rowNum = sheet.getLastRowNum() + 1;                     //取得最后一行的行号

            for (int i = startrow; i < rowNum; i++) {                    //行循环开始

                Enrolment enrolment = new Enrolment();
                HSSFRow row = sheet.getRow(i);                             //行
                int cellNum = row.getLastCellNum();                     //每行的最后一个单元格位置

                for (int j = startcol; j < cellNum; j++) {                //列循环开始

                    HSSFCell cell = row.getCell(Short.parseShort(j + ""));
                    String cellValue = null;
                    if (null != cell) {
                        switch (cell.getCellType()) {                     // 判断excel单元格内容的格式，并对其进行转换，以便插入数据库
                            case 0:
//                                cellValue = String.valueOf((int) cell.getNumericCellValue());
                                if(String.valueOf(cell.getNumericCellValue()).indexOf("E")==-1){
                                    cellValue= String.valueOf(cell.getNumericCellValue());
                                }else {
                                    cellValue= new DecimalFormat("#").format(cell.getNumericCellValue());
                                }
                                break;
                            case 1:
                                cellValue = cell.getStringCellValue();
                                break;
                            case 2  :
                                cellValue = cell.getNumericCellValue() + "";
                                // cellValue = String.valueOf(cell.getDateCellValue());
                                break;
                            case 3:
                                cellValue = "";
                                break;
                            case 4:
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case 5:
                                cellValue = String.valueOf(cell.getErrorCellValue());
                                break;
                        }

                    } else {
                        cellValue = "";
                    }
                    if (j == 0) {
                        enrolment.setPhone(cellValue);
                    }
                    if (j == 1) {
                        enrolment.setImtoken(cellValue);
                    }
                    if (j == 2) {
                        enrolment.setOrigin(cellValue);
                    }
                    if (j == 3) {
                        enrolment.setGhphone(cellValue);
                    }

                }
                enrolment.setAppendtime(new Date());
                varList.add(enrolment);
            }
        } catch (Exception e) {
        e.printStackTrace();
            System.out.println(e);
        }
        return varList;
    }


}
